{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Answers to Assignment 4 - Python Fundamentals II\n",
    "\n",
    "Complete the tasks below. Please turn in a single Jupyter notebook named `4_first_last.ipynb` (substitute your first and last name). Please run Kernel > Restart & Run All on your notebook before turning in."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Answer to A. Lists and loops\n",
    "\n",
    "1. Create a list of 10 random integers in the range of -100 to 100. \n",
    "2. Loop through that list using a for loop. Put the non-negative (positive or zero) integers into a new list. If negative integers are encountered, print a message saying that the value is negative and printing that value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[4, 57, -78, -13, -35, 97, -52, -55, 28, -21]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# one way\n",
    "list1 = random.sample(range(-100,100), 10)\n",
    "list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[-82, -3, 71, 7, -64, 88, 55, 11, 6, 66]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# another way\n",
    "list1 = [random.randrange(-100, 100) for i in range(10)]\n",
    "list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The value of -82 is negative\n",
      "The value of -3 is negative\n",
      "The value of -64 is negative\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[71, 7, 88, 55, 11, 6, 66]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list2 = []\n",
    "for item in list1:\n",
    "    if item >= 0:\n",
    "        list2.append(item)\n",
    "    else:\n",
    "        print('The value of %s is negative' % item)\n",
    "list2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Answer to B. Functions, lists, and loops\n",
    "\n",
    "1. Write a function that does what you did in part A but with the following differences: \n",
    "    - The input list can be any list of numbers.\n",
    "    - The function should take as a parameter a threshold for being included in the new list (e.g., if you want non-negative integers, the threshold would be 0, and the function would check if values are >= to this value).\n",
    "    - The printed message for failing to be included should also report the threshold parameter.\n",
    "    - The new list should be returned by the function.\n",
    "2. Execute the function on your list of 10 random integers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def new_list_from_criterion(mylist, mycutoff):\n",
    "    newlist = []\n",
    "    for item in mylist:\n",
    "        if item >= mycutoff:\n",
    "            newlist.append(item)\n",
    "        else:\n",
    "            print('The value of %s is not >= %s' % (item, mycutoff))\n",
    "    return(newlist)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The value of -82 is not >= 0\n",
      "The value of -3 is not >= 0\n",
      "The value of -64 is not >= 0\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[71, 7, 88, 55, 11, 6, 66]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_list_from_criterion(list1, -0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Answer to C. Dictionaries and list enumeration\n",
    "\n",
    "1. Create a two-dimensional list with 3 'rows' and 4 'columns' and a mixture of strings and integers. \n",
    "2. Loop through each element of the list and check if each element is a string or an integer. Save the strings as a dictionary with the index (row, column) as the key and the string as the value. Save the integers as a dictionary with the index (row, column) as the key and the integer as the value.\n",
    "3. Print out your dictionaries (no `print` command required)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[1, 'mango', 3, 'oranges'],\n",
       " ['peach', 'apple', 50, -50],\n",
       " [13, -11, 'bananas', 'grape']]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list2d = [[1, 'mango', 3, 'oranges'],\n",
    "          ['peach', 'apple', 50, -50],\n",
    "          [13, -11, 'bananas', 'grape']]\n",
    "list2d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "strdict = {}\n",
    "intdict = {}\n",
    "for row_index, row in enumerate(list2d):\n",
    "    for col_index, item in enumerate(row):\n",
    "        if isinstance(item, str):\n",
    "            strdict[(row_index, col_index)] = item\n",
    "        elif isinstance(item, int):\n",
    "            intdict[(row_index, col_index)] = item"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{(0, 1): 'mango',\n",
       " (0, 3): 'oranges',\n",
       " (1, 0): 'peach',\n",
       " (1, 1): 'apple',\n",
       " (2, 2): 'bananas',\n",
       " (2, 3): 'grape'}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "strdict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{(0, 0): 1, (0, 2): 3, (1, 2): 50, (1, 3): -50, (2, 0): 13, (2, 1): -11}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "intdict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Answer to D. List comprehension and saving files\n",
    "\n",
    "1. Create a list of 5 strings that are first and last names, e.g. `'Jon Doe'`. \n",
    "2. Use a list comprehension (a single-line command) to get the first initial from each name and store each string (e.g. `'J'`) in a new list. Print this list (no `print` command required).\n",
    "3. Repeat but store both the first and last initial (e.g. `'JD'`) in a new list. Print this list (no `print` command required).\n",
    "4. Save this second list to a text file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = ['Buzz Aldrin', 'Neil Armstrong', 'Gordon Cooper', 'James Lovell', 'Edgar Mitchell']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['B', 'N', 'G', 'J', 'E']"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "first_initial = [name[0] for name in names]\n",
    "first_initial"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['BA', 'NA', 'GC', 'JL', 'EM']"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "first_last_initial = [name.split(' ')[0][0] + name.split(' ')[1][0] for name in names]\n",
    "first_last_initial"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('../../data/assign4_q4.txt', 'w') as target:\n",
    "    for initials in first_last_initial:\n",
    "        target.write(initials)\n",
    "        target.write('\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Answer to E. Reading files, sets, and saving files\n",
    "\n",
    "1. Download this text file of past [World Series winners](https://github.com/cuttlefishh/python-for-data-analysis/blob/master/data/world_series_winners.txt). \n",
    "2. Read in the lines of the file to a list, so that each line is an element of the list. \n",
    "3. Create a new list with just those list elements that contain 'New York'; print that list, making sure there's not an extra newline character between each line. Print this list (no `print` command required).\n",
    "4. Use the `set` class to convert the list of all World Series winners to a list of unique values. Print this list (no `print` command required).\n",
    "5. Write the output to a new file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "# one way\n",
    "with open ('../../data/world_series_winners.txt', \"r\") as f:\n",
    "    winners = f.read().splitlines()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "# another way\n",
    "with open('../../data/world_series_winners.txt', 'r') as f:\n",
    "    winners = f.readlines()\n",
    "winners = [team.rstrip() for team in winners]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['New York Giants',\n",
       " 'New York Giants',\n",
       " 'New York Giants',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Giants',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Giants',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Mets',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Mets',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees',\n",
       " 'New York Yankees']"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_york_winners = [team for team in winners if 'New York' in team]\n",
    "new_york_winners"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Anaheim Angels',\n",
       " 'Arizona Diamondbacks',\n",
       " 'Atlanta Braves',\n",
       " 'Baltimore Orioles',\n",
       " 'Boston Americans',\n",
       " 'Boston Braves',\n",
       " 'Boston Red Sox',\n",
       " 'Brooklyn Dodgers',\n",
       " 'Chicago Cubs',\n",
       " 'Chicago White Sox',\n",
       " 'Cincinnati Reds',\n",
       " 'Cleveland Indians',\n",
       " 'Detroit Tigers',\n",
       " 'Florida Marlins',\n",
       " 'Houston Astros',\n",
       " 'Kansas City Royals',\n",
       " 'Los Angeles Dodgers',\n",
       " 'Milwaukee Braves',\n",
       " 'Minnesota Twins',\n",
       " 'New York Giants',\n",
       " 'New York Mets',\n",
       " 'New York Yankees',\n",
       " 'No World Series',\n",
       " 'Oakland Athletics',\n",
       " 'Philadelphia Athletics',\n",
       " 'Philadelphia Phillies',\n",
       " 'Pittsburgh Pirates',\n",
       " 'San Francisco Giants',\n",
       " 'St. Louis Cardinals',\n",
       " 'Toronto Blue Jays',\n",
       " 'Washington Senators'}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unique_winners = set(winners)\n",
    "unique_winners"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('../../data/assign4_q5.txt', 'w') as target:\n",
    "    for team in sorted(list(unique_winners)):\n",
    "        target.write(team)\n",
    "        target.write('\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
